#!-*-codding:utf-8
import sys
import os
from multiprocessing import Process


def runStart(package, package_list, type_):
    if 1 == type_:
        obj = __import__("{}".format(package))
        if hasattr(obj, "startBs"):
            obj.startBs()
            del obj
    else:
        obj = __import__("{}".format(package))
        if hasattr(eval("obj.{}".format(".".join(package_list[1:]))), "startBs"):
            eval("obj.{}.startBs()".format(".".join(package_list[1:])))
            del obj


class RunAll():
    def __init__(self):
        pass

    def run(self):
        path_ = os.path.split(os.path.abspath(sys.argv[0]))[0]
        name = os.path.split(os.path.abspath(sys.argv[0]))[1]

        for path, dir1, filenames in os.walk(path_):
            for fn in filenames:
                if path == path_ and (fn == name or os.path.basename(__file__) == fn):
                    continue

                if not fn.endswith(".py"):
                    continue
                if fn == "__init__.py":
                    continue
                package_list = [x for x in path.split(os.sep) if x!='' and x not in path_.split(os.sep)]
                package_list.append(fn.replace(".py",""))
                sys.argv[0] = os.path.join(path_, fn)
                try:
                    type_ = 0
                    if len(package_list) == 1:
                        package_ = ".".join(package_list)
                        type_ = 1
                    else:
                        package_ = ".".join(package_list)

                    p = Process(target=runStart, args=(package_, package_list, type_))
                    p.name = package_
                    p.start()
                    p.join()

                except Exception as e:
                    print "exception", e


